package com.beeantec.jnrerc.modules.mission.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beeantec.jnrerc.core.annon.LogInject;
import com.beeantec.jnrerc.core.api.ApiRest;
import com.beeantec.jnrerc.core.api.controller.BaseController;
import com.beeantec.jnrerc.core.enums.*;
import com.beeantec.jnrerc.dto.MemberVo;
import com.beeantec.jnrerc.dto.request.MissionDetailReqDTO;
import com.beeantec.jnrerc.dto.request.MissionJionReqDTO;
import com.beeantec.jnrerc.dto.request.MissionReqDTO;
import com.beeantec.jnrerc.dto.request.TeamMemberReqDTO;
import com.beeantec.jnrerc.dto.response.*;
import com.beeantec.jnrerc.entity.*;
import com.beeantec.jnrerc.modules.member.service.DynamicService;
import com.beeantec.jnrerc.modules.member.service.GrowRecordService;
import com.beeantec.jnrerc.modules.member.service.MemberService;
import com.beeantec.jnrerc.modules.message.service.MessageService;
import com.beeantec.jnrerc.modules.mission.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(tags={"任务"})
@RestController
@RequestMapping("/api/mission")
public class MissionController extends BaseController {

    @Autowired
    private MissionService missionService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private TeamMissionService teamMissionService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private PlanService planService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private DistributeService distributeService;

    @Autowired
    private GrowRecordService growRecordService;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private TeamMemberService teamMemberService;
    /**
     * 发布任务
     * @return
     */
    @LogInject(title = "发布任务")
    @CrossOrigin
    @ApiOperation(value = "发布任务")
    @RequestMapping(value = "/release", method = {RequestMethod.POST})
    public ApiRest<String> release(@RequestBody MissionReqDTO missionReqDTO) {
        Member member = memberService.getById(missionReqDTO.getMemberId());
        GrowRecord growRecord = new GrowRecord();
        MemberDynamic memberDynamic = new MemberDynamic();
        memberDynamic.setMemberId(member.getMemberId().longValue());
        memberDynamic.setCreateTime(new Date());
        if (missionReqDTO.getType()==0){
            memberDynamic.setTitle("我发布了一个悬赏，快来报名参与吧！");
            memberDynamic.setType(DynamicEnum.REWARD.getCode());
        }else {
            memberDynamic.setTitle("我发布了一个竞标，快来报名参与吧！");
            memberDynamic.setType(DynamicEnum.BIDDING.getCode());
        }
        Integer count =0;
       if (missionReqDTO.getAwardType()== 0){
           if (member.getIntegral()< missionReqDTO.getAward()){
               return failure("任务发布失败,积分值不足");
           }else {
               count = member.getIntegral()- missionReqDTO.getAward();
               member.setIntegral(count);
               growRecord.setType(0);
           }
       }else {
           if (member.getCharm()< missionReqDTO.getAward()){
               return failure("任务发布失败,魅力值不足");
           }else {
               count = member.getCharm()- missionReqDTO.getAward();
               member.setCharm(count);
               growRecord.setType(1);
           }
       }
        Mission mission = new Mission();
        mission.setAward(missionReqDTO.getAward());
        mission.setContent(missionReqDTO.getContent());
        mission.setAwardType(missionReqDTO.getAwardType());
        mission.setCreateTime(new Date(System.currentTimeMillis()));
        mission.setCreatorId(missionReqDTO.getMemberId());
        mission.setStatus(MissionStateEnum.RELEASE.getCode());
        mission.setEndTime(missionReqDTO.getEndTime());
        mission.setStartTime(missionReqDTO.getStartTime());
        mission.setTitle(missionReqDTO.getTitiel());
        mission.setType(missionReqDTO.getType());
        if (missionService.saveOrUpdate(mission)){
            memberService.saveOrUpdate(member);
            growRecord.setCount((-missionReqDTO.getAward()));
            growRecord.setCreateTime(new Date());
            growRecord.setDes("发布任务");
            growRecord.setMemberId(member.getMemberId().longValue());
            boolean gr = growRecordService.save(growRecord);
            memberDynamic.setItemId(mission.getId().longValue());
            dynamicService.save(memberDynamic);
            return success("任务发布成功");
        }
        return failure("任务发布失败");
    }

    /**
     * 删除任务
     * @return
     */
    @LogInject(title = "删除任务")
    @CrossOrigin
    @ApiOperation(value = "删除任务")
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    public ApiRest<String> delete(@RequestBody MissionDetailReqDTO missionDetailReqDTO) {
       if (missionService.removeById(missionDetailReqDTO.getMissionId())){
           return success("删除任务成功");
       }
        return success("删除任务失败");
    }

    /**
     * 用户参与任务记录
     * @return
     */
    @LogInject(title = "获取用户参与任务记录")
    @CrossOrigin
    @ApiOperation(value = "获取用户参与任务记录")
    @RequestMapping(value = "/record", method = {RequestMethod.GET})
    public ApiRest<List<MissionRecordRespDTO>> record(@RequestHeader("token") String token) {
        List<MissionRecordRespDTO> list = new ArrayList<>();
        MemberVo memberVo = memberService.token(token);
        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
        teamQueryWrapper.lambda().eq(Team::getCreatorId,memberVo.getMemberId());
        QueryWrapper<TeamMission> teamMissionQueryWrapper = new QueryWrapper<>();
        Team team =  teamService.getOne(teamQueryWrapper);
        if (null==team){
            return success(list);
        }
        teamMissionQueryWrapper.lambda().eq(TeamMission::getTeamId,team.getId());
        List<TeamMission> teamMissionList = new ArrayList<>();
        teamMissionList = teamMissionService.list(teamMissionQueryWrapper);
        for (TeamMission teamMission:teamMissionList){
            QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
            missionQueryWrapper.lambda().eq(Mission::getId,teamMission.getMissionId());
            Mission mission = missionService.getOne(missionQueryWrapper);
            if(null==mission){
                break;
            }
            MissionRecordRespDTO missionRecordRespDTO = new MissionRecordRespDTO();
            missionRecordRespDTO.setState(mission.getStatus());
            missionRecordRespDTO.setEndTime(mission.getEndTime());
            missionRecordRespDTO.setStartTime(mission.getStartTime());
            missionRecordRespDTO.setTitle(mission.getTitle());
            missionRecordRespDTO.setMissionId(mission.getId());
            missionRecordRespDTO.setAwardType(mission.getAwardType());
            missionRecordRespDTO.setCreateTime(mission.getCreateTime());
            QueryWrapper<TeamMission> teamMissionQueryWrapper1 = new QueryWrapper<>();
            teamMissionQueryWrapper1.lambda().eq(TeamMission::getMissionId,mission.getId());
            List<TeamMission> teamMissionList1 = new ArrayList<>();
            teamMissionList1 = teamMissionService.list(teamMissionQueryWrapper1);
            missionRecordRespDTO.setCount(teamMissionList1.size());
            missionRecordRespDTO.setAward(mission.getAward());
            QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
            planQueryWrapper.lambda().eq(Plan::getMissionId,teamMission.getMissionId())
                    .eq(Plan::getStatus, PlanStateEnum.PASS.getCode());
            Plan passPlan = planService.getOne(planQueryWrapper);
            if (null==passPlan){
                missionRecordRespDTO.setTeamName("无");
            }else {
                missionRecordRespDTO.setTeamName( memberService.getById(teamService
                        .getById(passPlan.getTeamId()).getCreatorId()).getNickName());
            }
            list.add(missionRecordRespDTO);
        }
        list.sort(Comparator.comparing(MissionRecordRespDTO::getCreateTime).reversed());
        return success(list);
    }


    /**
     * 获取用户发布任务记录
     * @return
     */
    @LogInject(title = "获取用户发布任务记录")
    @CrossOrigin
    @ApiOperation(value = "获取用户发布任务记录")
    @RequestMapping(value = "/release/record", method = {RequestMethod.GET})
    public ApiRest<List<MissionRecordRespDTO>> releaseRecord(@RequestHeader("token") String token) {
        List<MissionRecordRespDTO> list = new ArrayList<>();
        MemberVo memberVo = memberService.token(token);
        QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
        missionQueryWrapper.lambda().eq(Mission::getCreatorId,memberVo.getMemberId()).orderByDesc(Mission::getCreateTime);
        List<Mission> missionList = missionService.list(missionQueryWrapper);
        for (Mission mission:missionList){
            MissionRecordRespDTO missionRecordRespDTO = new MissionRecordRespDTO();
            missionRecordRespDTO.setState(mission.getStatus());
            missionRecordRespDTO.setEndTime(mission.getEndTime());
            missionRecordRespDTO.setStartTime(mission.getStartTime());
            missionRecordRespDTO.setTitle(mission.getTitle());
            missionRecordRespDTO.setAwardType(mission.getAwardType());
            missionRecordRespDTO.setAward(mission.getAward());
            missionRecordRespDTO.setMissionId(mission.getId());
            missionRecordRespDTO.setCreateTime(mission.getCreateTime());
            QueryWrapper<TeamMission> teamMissionQueryWrapper = new QueryWrapper<>();
            teamMissionQueryWrapper.lambda().eq(TeamMission::getMissionId,mission.getId());
            List<TeamMission> teamMissionList = new ArrayList<>();
            teamMissionList = teamMissionService.list(teamMissionQueryWrapper);
            missionRecordRespDTO.setCount(teamMissionList.size());
            QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
            planQueryWrapper.lambda().eq(Plan::getMissionId,mission.getId())
                    .eq(Plan::getStatus, PlanStateEnum.PASS.getCode());
            Plan passPlan = planService.getOne(planQueryWrapper);
            if (null==passPlan){
                missionRecordRespDTO.setTeamName("无");
            }else {
                missionRecordRespDTO.setTeamName( memberService.getById(teamService
                        .getById(passPlan.getTeamId()).getCreatorId()).getNickName());
            }
            list.add(missionRecordRespDTO);
        }
        return success(list);
    }

    /**
     * 任务详情
     * @return
     */
    @LogInject(title = "获取任务详情")
    @CrossOrigin
    @ApiOperation(value = "获取任务详情")
    @RequestMapping(value = "/detail", method = {RequestMethod.GET})
    public ApiRest<MissionDetailRespDTO> detail(@RequestParam("missionId") Long missionId) {
        MissionDetailRespDTO missionDetailRespDTO = new MissionDetailRespDTO();
        List<TeamPlanRespDTO> teamPlanRespDTOList = new ArrayList<>();
        missionDetailRespDTO.setDetail(missionService.getById(missionId));
        QueryWrapper<TeamMission> teamMissionQueryWrapper = new QueryWrapper<>();
        teamMissionQueryWrapper.lambda().eq(TeamMission::getMissionId,missionId);
        List<TeamMission>  teamMissions = teamMissionService.list(teamMissionQueryWrapper);
        for (TeamMission teamMission:teamMissions){
            TeamPlanRespDTO teamPlanRespDTO = new TeamPlanRespDTO();
            Member member = memberService.getById(teamService.getById(teamMission.getTeamId()).getCreatorId());
            teamPlanRespDTO.setTeamName(member.getNickName());
            teamPlanRespDTO.setCover(member.getAvatarUrl());
            QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
            planQueryWrapper.lambda().eq(Plan::getTeamId,teamMission.getTeamId())
                    .eq(Plan::getMissionId,missionId);
            BeanUtils.copyProperties(planService.getOne(planQueryWrapper),teamPlanRespDTO);
            teamPlanRespDTO.setAssign(teamMission.getAssign());
            teamPlanRespDTOList.add(teamPlanRespDTO);
        }
        missionDetailRespDTO.setList(teamPlanRespDTOList);
        return success(missionDetailRespDTO);
    }


    /**
     * 任务状态变更 type(0中标1验收2完成)
     * @return
     */
    @LogInject(title = "任务状态变更")
    @CrossOrigin
    @ApiOperation(value = "任务状态变更")
    @RequestMapping(value = "/change", method = {RequestMethod.GET})
    public ApiRest<Boolean> changeMissionState(@RequestParam("missionId") Long missionId,@RequestParam("planId") Long planId,@RequestParam("type") Integer type) {
        Mission mission = missionService.getById(missionId);
        Plan plan = planService.getById(planId);
        if (null==mission){
            return failure(false);
        }
        if (null==plan){
            return failure(false);
        }
        if(type==0){
            mission.setStatus(MissionStateEnum.CHOOSE.getCode());
            plan.setStatus(PlanStateEnum.PASS.getCode());
            if ( missionService.saveOrUpdate(mission)&&planService.saveOrUpdate(plan)){
                MemberDynamic memberDynamic = new MemberDynamic();
                memberDynamic.setMemberId(mission.getCreatorId());
                memberDynamic.setTitle("我的任务已经有人中标了，快来看看吧");
                memberDynamic.setCreateTime(new Date());
                memberDynamic.setItemId(mission.getId());
                if (mission.getType()==0){
                    memberDynamic.setType(DynamicEnum.REWARD.getCode());
                }else {
                    memberDynamic.setType(DynamicEnum.BIDDING.getCode());
                }
                dynamicService.save(memberDynamic);
                return success(true);
            }
        }
        if (type==1){
            mission.setStatus(MissionStateEnum.COMMIT.getCode());
            if (missionService.saveOrUpdate(mission)){
                return success(true);
            }
        }
        if (type==2){
            mission.setStatus(MissionStateEnum.ASSIGN_REWARDS.getCode());
            if (missionService.saveOrUpdate(mission)){
                return success(true);
            }
        }
        return failure(false);
    }


    /**
     * 任务状态变更
     * @return
     */
    @LogInject(title = "用户是否已参与任务")
    @CrossOrigin
    @ApiOperation(value = "用户是否已参与任务")
    @RequestMapping(value = "/hasJion", method = {RequestMethod.GET})
    public ApiRest<Boolean> hasJion(@RequestParam("memberId") Long memberId,@RequestParam("missionId") Long missionId) {
        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
        teamQueryWrapper.lambda().eq(Team::getCreatorId,memberId);
        Team team = teamService.getOne(teamQueryWrapper);
        if (null==team) {
           return success(false);
        }
            QueryWrapper<TeamMission> teamMissionQueryWrapper = new QueryWrapper<>();
            teamMissionQueryWrapper.lambda().eq(TeamMission::getTeamId,team.getId())
            .eq(TeamMission::getMissionId,missionId);
           TeamMission teamMission = teamMissionService.getOne(teamMissionQueryWrapper);
           if (null==teamMission){
               return success(false);
           }
        return success(true);
    }


    /**
     * 参与任务
     * @return
     */
    @LogInject(title = "参与任务")
    @CrossOrigin
    @ApiOperation(value = "参与任务")
    @RequestMapping(value = "/join", method = {RequestMethod.POST})
    public ApiRest<Boolean> join(@RequestBody MissionJionReqDTO missionJionReqDTO) {
        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
        teamQueryWrapper.lambda().eq(Team::getCreatorId,missionJionReqDTO.getMemberId());
        Team team = teamService.getOne(teamQueryWrapper);
        if (null==team){
            team = new Team();
            team.setCreatorId(missionJionReqDTO.getMemberId());
            teamService.save(team);
        }

        Team userTeam = teamService.getOne(teamQueryWrapper);

        QueryWrapper<TeamMission> teamMissionQueryWrapper = new QueryWrapper<>();
        teamMissionQueryWrapper.lambda().eq(TeamMission::getMissionId,missionJionReqDTO.getMissionId())
                .eq(TeamMission::getTeamId,userTeam.getId());
        TeamMission teamMission = teamMissionService.getOne(teamMissionQueryWrapper);
        if (null==teamMission){
            teamMission = new TeamMission();
            teamMission.setMissionId(missionJionReqDTO.getMissionId());
            teamMission.setTeamId(userTeam.getId());
            teamMission.setAssign(missionJionReqDTO.getAssign());
            boolean teamMissionResult =   teamMissionService.save(teamMission);
            if (!teamMissionResult){
                return failure("加入任务失败",false);
            }
        }else {
            return failure("请勿重复加入",false);
        }
        Plan plan = new Plan();
        plan.setContent(missionJionReqDTO.getContent());
        plan.setRemark(missionJionReqDTO.getRemark());
        plan.setMissionId(missionJionReqDTO.getMissionId());
        plan.setCreateTime(new Date());
        plan.setTime(missionJionReqDTO.getTime());
        plan.setStatus(PlanStateEnum.NOPASS.getCode());
        plan.setTeamId(userTeam.getId());
       boolean result =  planService.save(plan);
       if (!result){
           return failure("加入任务失败",false);
       }
       Mission mission = missionService.getById(missionJionReqDTO.getMissionId());
       mission.setStatus(MissionStateEnum.JION.getCode());
       missionService.saveOrUpdate(mission);
       MemberMsg message = new MemberMsg();
       message.setCreateTime(new Date());
       message.setType(MessageTypeEnum.MISSION.getCode());
       message.setReadState(0);
       message.setUserId(mission.getCreatorId().intValue());
       message.setContent("你发布的任务"+mission.getTitle()+"有人揭榜了，快去看看是谁吧");
       messageService.save(message);
        TeamMember teamMember = new TeamMember();
        teamMember.setMemberId(missionJionReqDTO.getMemberId());
        teamMember.setMissionId(missionJionReqDTO.getMissionId());
        teamMember.setLeader(1);
        teamMember.setTeamId(team.getId());
        teamMemberService.save(teamMember);
        if (null!=missionJionReqDTO.getMateList()&&!missionJionReqDTO.getMateList().isEmpty()){
            List<TeamMember> mateList = new ArrayList<>();
            for (Integer memebrId: missionJionReqDTO.getMateList()){
                TeamMember mateMember = new TeamMember();
                mateMember.setMemberId(memebrId.longValue());
                mateMember.setMissionId(missionJionReqDTO.getMissionId());
                mateMember.setLeader(0);
                mateMember.setTeamId(team.getId());
                mateList.add(mateMember);
            }
            teamMemberService.saveBatch(mateList);
        }


        return success("加入任务成功",true);
    }

    /**
     * 获取任务列表
     * @return
     */
    @LogInject(title = "获取任务列表")
    @CrossOrigin
    @ApiOperation(value = "获取任务列表")
    @RequestMapping(value = "/list", method = {RequestMethod.GET})
    public ApiRest<List<MissionRespDTO>> list(@RequestParam("state") Integer state, @RequestParam("type") Integer type) {
        List<MissionRespDTO> respDTOList = new ArrayList<>();
        List<Mission> missionList = new ArrayList<>();
        if (state==0){
            QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
            missionQueryWrapper.lambda().eq(Mission::getType,type).orderByDesc(Mission::getCreateTime);
            missionList = missionService.list(missionQueryWrapper);
        }else if (state==1){
            QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
            missionQueryWrapper.lambda().eq(Mission::getType,type)
            .ne(Mission::getStatus,MissionStateEnum.RELEASE.getCode())
                    .ne(Mission::getStatus,MissionStateEnum.ASSIGN_REWARDS.getCode()).orderByDesc(Mission::getCreateTime);
            missionList = missionService.list(missionQueryWrapper);
        }else if (state==2){
            QueryWrapper<Mission> missionQueryWrapper = new QueryWrapper<>();
            missionQueryWrapper.lambda().eq(Mission::getType,type)
                   .eq(Mission::getStatus,MissionStateEnum.ASSIGN_REWARDS.getCode()).orderByDesc(Mission::getCreateTime);
            missionList = missionService.list(missionQueryWrapper);
        }
        for (Mission mission:missionList){
            MissionRespDTO missionRespDTO = new MissionRespDTO();
            missionRespDTO.setMission(mission);
            QueryWrapper<TeamMission> teamMissionQueryWrapper = new QueryWrapper<>();
            teamMissionQueryWrapper.lambda().eq(TeamMission::getMissionId,mission.getId());
            List<TeamMission> teamMissionList = new ArrayList<>();
            teamMissionList = teamMissionService.list(teamMissionQueryWrapper);
            missionRespDTO.setCount(teamMissionList.size());
            respDTOList.add(missionRespDTO);
        }
        return success(respDTOList);
    }


    /**
     * 分配奖励
     * @return
     */
    @LogInject(title = "分配奖励")
    @CrossOrigin
    @ApiOperation(value = "分配奖励")
    @RequestMapping(value = "/distribute", method = {RequestMethod.POST})
    public ApiRest<String> distribute(@RequestBody Distribute distribute) {
        Mission mission = missionService.getById(distribute.getMissionId());
        boolean result = distributeService.save(distribute);
        if (result){
            mission.setStatus(MissionStateEnum.FINISH.getCode());
            missionService.saveOrUpdate(mission);
            return success("提交成功！");
        }
        return failure("提交失败");
    }

    /**
     * 分配奖励
     * @return
     */
    @LogInject(title = "添加团队成员")
    @CrossOrigin
    @ApiOperation(value = "添加团队成员")
    @RequestMapping(value = "/add/teammate", method = {RequestMethod.POST})
    public ApiRest<String> addTeamMate(@RequestBody TeamMemberReqDTO teamMemberReqDTO) {
        TeamMember teamMember = new TeamMember();
        teamMember.setTeamId(teamMemberReqDTO.getTeamId());
        teamMember.setMemberId(teamMember.getMemberId());
        teamMember.setMissionId(teamMember.getMissionId());
        teamMember.setLeader(0);
        if (teamMemberService.save(teamMember)){
            return failure("添加成员成功");
        }
        return failure("添加成员失败");
    }


    /**
     * 分配奖励
     * @return
     */
    @LogInject(title = "获取任务团队成员列表")
    @CrossOrigin
    @ApiOperation(value = "获取任务团队成员列表")
    @RequestMapping(value = "/list/teammate", method = {RequestMethod.GET})
    public ApiRest<List<TeamMemberRespDTO>> getTeammateList(@RequestParam("teamId")Long teamId, @RequestParam("missionId")Long missionId) {
        List<TeamMember> teamMemberList = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        List<TeamMemberRespDTO> teamMemberRespDTOS = new ArrayList<>();
        List<Member> memberList = new ArrayList<>();
        Team team = teamService.getById(teamId);
        QueryWrapper<TeamMember> teamMemberQueryWrapper = new QueryWrapper<>();
      teamMemberQueryWrapper.lambda().eq(TeamMember::getTeamId,teamId).eq(TeamMember::getMissionId,missionId);
        teamMemberList =teamMemberService.list(teamMemberQueryWrapper);
        for (TeamMember teamMember:teamMemberList){
            ids.add(teamMember.getMemberId().intValue());
        }
        if (!ids.isEmpty()){
            memberList = memberService.listByIds(ids);
        }
        for (Member member:memberList){
            TeamMemberRespDTO teamMemberRespDTO = new TeamMemberRespDTO();
            BeanUtils.copyProperties(member,teamMemberRespDTO);
            if (teamMemberRespDTO.getMemberId().equals(team.getCreatorId().intValue())){
                teamMemberRespDTO.setLeader(true);
            }else {
                teamMemberRespDTO.setLeader(false);
            }
            teamMemberRespDTOS.add(teamMemberRespDTO);
        }
        return success(teamMemberRespDTOS);
    }


}
